package cn.occgmat.controller;

import cn.occgmat.entity.Admin;
import cn.occgmat.service.AdminService;
import cn.occgmat.util.BaseResponse;
import cn.occgmat.util.StatusCode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author shimmer
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    /**
     * J2ee依赖注入，默认by name
     */
    @Resource
    private AdminService adminService;

    /**
     * 分页查询管理员信息
     *
     * @param page  当前页数
     * @param limit 每页数
     * @return 一页数据
     */
    @GetMapping(value = "findAllLimit")
    public BaseResponse<Admin> findAllLimit(int page, int limit) {
        return adminService.findAllLimit(page, limit);
    }

    /**
     * 管理员登录
     *
     * @param admin 管理员
     * @return 查询结果json数据
     */
    @PostMapping("admin_login")
    public BaseResponse<?> adminLogin(@RequestBody Admin admin, HttpSession session) {
        return adminService.findLogin(admin, session);
    }

    /**
     * 从session中获取管理员信息
     */
    @GetMapping("getInfoBySession")
    public Admin getInfoBySession(HttpSession session) {
        return (Admin) session.getAttribute("admin");
    }

    /**
     * 管理员退出登录
     *
     * @param session session
     */
    @GetMapping(value = "admin_logout")
    public void adminLogout(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        this.adminService.logOut(session);
        try {
            response.sendRedirect(request.getContextPath() + "/login.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新管理员信息
     *
     * @param admin   管理员
     * @param session 服务器session
     * @return 更新状态
     */
    @PostMapping("update")
    public BaseResponse<?> update(@RequestBody Admin admin, HttpSession session) {
        // 更新数据库
        String adminName = admin.getAdminName();
        String sex = admin.getSex();
        String phoneNumber = admin.getPhoneNumber();
        int result = adminService.adminUpdate(admin);
        if (result <= 0) {
            throw new RuntimeException("更新管理员信息失败！");
        }
        // 更新session数据
        Admin oldAdmin = (Admin) session.getAttribute("admin");
        if (oldAdmin == null) {
            throw new RuntimeException("session中没有管理员数据！");
        }
        oldAdmin.setAdminName(adminName);
        oldAdmin.setSex(sex);
        oldAdmin.setPhoneNumber(phoneNumber);
        session.setAttribute("admin", oldAdmin);
        return new BaseResponse<>(StatusCode.Success);
    }

}
